<?php

use console\db\Migration;
use yii\db\Query;

/**
 * 用户收藏的动态格式化
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300020_000017_t_sns_dynamic_favorite_format extends Migration {

    /**
     * @inheritdoc
     */
    public $tableName = '{{%user_favorite}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $query = (new Query())->from($this->tableName)
        ->where(['model' => 'thread']);
        $this->handleProgress($query, [$this, 'evenDule']);
    }

    /**
     * 处理结果
     * @param Migration $migration
     * @param array $rows
     */
    public static function evenDule($migration, $rows) {
        if (empty($rows)) {
            return;
        }
        $connect = $migration->db->createCommand();
        $ids = [];
        foreach ($rows as $row) {
            $exists = (new Query())->from('{{%sns_dynamic}}')
            ->where(['id' => $row['model_id']])
            ->exists();
            if ($exists) {
                $connect->update($migration->tableName, [
                    'model' => 'sns_dynamic',
                ], ['id' => $row['id']])->execute();
            } else {
                $ids[] = $row['id'];
            }
        }
        if (!empty($ids)) {
            $connect->delete($migration->tableName, ['id' => $ids])->execute();
        }
    }

}
